/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Panel;

import DAO.DangKyLamViecDAO;
import DAO.LichTrinhDAO;
import DAO.NhanVienDAO;
import DAO.TauDAO;
import DAO.TuyenDuongDAO;
import OBJECT.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.AbstractListModel;
import javax.swing.ComboBoxModel;
import java.util.*;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
import util.Utils;

/**
 *
 * @author Steven
 */
public class DangKyLichLamViec extends javax.swing.JPanel {

    private MyComboBoxModel NhanVienListModel = new MyComboBoxModel();
    private MyComboBoxModel TauListModel = new MyComboBoxModel();
    private MyComboBoxModel TuyenDuongListModel = new MyComboBoxModel();
    private MyComboBoxModel ThoiGianKhoiHanhVaThoiGianDenListModel = new MyComboBoxModel();
    
    private List<Tau> DanhSachTau = null;
    private List<TuyenDuong> DanhSachTuyenDuong = null;
    private List<DangKyLamViec> DanhSachDangKyLamViec = null;
    private int DongDangKyLamViecDuocChon = -1;
    private List<LichTrinh> DanhSachLichTrinhTheoTauVaTuyenDuong = null;
    private DefaultTableModel model = null;
    
    private DangKyLamViecDAO dklvDao = null;
    private LichTrinhDAO ltDao = null;
    private NhanVienDAO nvDao = null;
    private TauDAO tDao = null;
    private TuyenDuongDAO tdDao = null;
    /**
     * Creates new form DangKyLichLamViec
     */
    public DangKyLichLamViec() {
        initComponents();
        handleComboboxItemChangeEvent();
        initData();
    }

    public DangKyLichLamViec(String User ,String Pass,String port,String DataBase,String Host){
        initComponents();
        
        dklvDao = new DangKyLamViecDAO(User, Pass, port, DataBase, Host);
        ltDao = new LichTrinhDAO(User, Pass, port, DataBase, Host);
        nvDao = new NhanVienDAO(User, Pass, port, DataBase, Host);
        tDao = new TauDAO(User, Pass, port, DataBase, Host);
        tdDao = new TuyenDuongDAO(User, Pass, port, DataBase, Host);
        
        handleComboboxItemChangeEvent();
        initData();
    }
    
    private void handleComboboxItemChangeEvent(){
        
        MyItemListener actionListener = new MyItemListener();
        JCBTau.addItemListener(actionListener);
        JCBTuyenDuong.addItemListener(actionListener);
    }
    
    class MyItemListener implements ItemListener {
    // This method is called only if a new item has been selected.
        @Override
        public void itemStateChanged(ItemEvent evt) {
            JComboBox cb = (JComboBox)evt.getSource();

            // Get the affected item
            Object item = evt.getItem();

            if (evt.getStateChange() == ItemEvent.SELECTED) {
                // Item was just selected
                listDepartureTimeAndArriveTime();
            } else if (evt.getStateChange() == ItemEvent.DESELECTED) {
                // Item is no longer selected
                
            }
        }
    }
    
    private void listDepartureTimeAndArriveTime(){
        ThoiGianKhoiHanhVaThoiGianDenListModel.clear();
        int MaTuyenDuong = DanhSachTuyenDuong.get(TuyenDuongListModel.getSelectedIndex()).getMaTuyenDuong();
        int MaTau = DanhSachTau.get(TauListModel.getSelectedIndex()).getMaTau();
        DanhSachLichTrinhTheoTauVaTuyenDuong = ltDao.LayLichTrinhTheoTuyenDuongVaTau(MaTuyenDuong, MaTau);
        if(DanhSachLichTrinhTheoTauVaTuyenDuong.size() > 0){
            for(LichTrinh lt: DanhSachLichTrinhTheoTauVaTuyenDuong){
                ThoiGianKhoiHanhVaThoiGianDenListModel.add(lt.getTGKhoiHanh() + " - " + lt.getTGDen());
            }
            ThoiGianKhoiHanhVaThoiGianDenListModel.setSelectedItem(0);
        }
    }
    
    private void initData(){
        
        
        DanhSachTau = tDao.LayDanhSachTau();
        if(DanhSachTau.size() > 0){
            for(Tau t: DanhSachTau){
                TauListModel.add(t.getTenTau());
            }
            TauListModel.setSelectedItem(0);
        }
        
        
        DanhSachTuyenDuong = tdDao.LayDanhSachTuyenDuong();
        if(DanhSachTuyenDuong.size() > 0){
            for(TuyenDuong td: DanhSachTuyenDuong){
                TuyenDuongListModel.add(td.getTenTuyenDuong());
            }
            TuyenDuongListModel.setSelectedItem(0);
        }
        
        if(TauListModel.model.size() > 0 && TuyenDuongListModel.model.size() > 0){
            listDepartureTimeAndArriveTime();
        }
        
        model = (DefaultTableModel) JTDanhSachDangKyLichLamViec.getModel();
        DanhSachDangKyLamViec = dklvDao.LayDanhSachDangKyLamViec();
        
        for(DangKyLamViec dklv: DanhSachDangKyLamViec){
            insertIntoTable(dklv);
        }
        
        JTFNgayDangKy.setText(Utils.getCurrentDate("dd-MM-yyyy"));
    }
    
    private int insertIntoTable(DangKyLamViec dklv){
        try {
            Object[] data = {dklv.getTenNhanVien(), dklv.getTenTuyenDuong(), dklv.getTenTau(), dklv.getThoiGianKhoiHanh(), dklv.getThoiGianDen(), dklv.getNgayDangKy()};
            model.addRow(data);
        } catch (Exception e) {
            System.err.println(e.getMessage());
            return 0;
        }
        
        return 1;    
    }
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        JCBTau = new javax.swing.JComboBox();
        jLabel4 = new javax.swing.JLabel();
        JCBTuyenDuong = new javax.swing.JComboBox();
        jLabel5 = new javax.swing.JLabel();
        JTFNgayDangKy = new javax.swing.JTextField();
        JBDangKy = new javax.swing.JButton();
        JBHuy = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        jComboBox1 = new javax.swing.JComboBox();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        JTDanhSachDangKyLichLamViec = new javax.swing.JTable();

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Thông tin"));

        jLabel2.setText("Tên Tàu: ");

        JCBTau.setModel(TauListModel);

        jLabel4.setText("Tên Tuyến Đường: ");

        JCBTuyenDuong.setModel(TuyenDuongListModel);

        jLabel5.setText("Ngày Đăng Ký: ");

        JTFNgayDangKy.setEditable(false);

        JBDangKy.setText("Đăng ký");
        JBDangKy.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                JBDangKyActionPerformed(evt);
            }
        });

        JBHuy.setText("Hủy");
        JBHuy.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                JBHuyActionPerformed(evt);
            }
        });

        jLabel3.setText("Thời gian khởi hành và thời gian đến: ");

        jComboBox1.setModel(ThoiGianKhoiHanhVaThoiGianDenListModel);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel3))
                        .addGap(10, 10, 10)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jComboBox1, 0, 151, Short.MAX_VALUE)
                            .addComponent(JCBTau, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                    .addComponent(JBDangKy, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addComponent(JBHuy, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(45, 45, 45)
                                .addComponent(jLabel5)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 36, Short.MAX_VALUE))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jLabel4)
                                .addGap(18, 18, 18)))
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(JCBTuyenDuong, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(JTFNgayDangKy, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addGap(39, 39, 39))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(JTFNgayDangKy, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3)
                    .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(20, 20, 20)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jLabel4)
                    .addComponent(JCBTuyenDuong, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(JCBTau, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(JBDangKy)
                    .addComponent(JBHuy))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Danh sách đăng ký lịch làm việc"));

        JTDanhSachDangKyLichLamViec.setAutoCreateRowSorter(true);
        JTDanhSachDangKyLichLamViec.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Nhân Viên", "Tàu", "Tuyến Đường", "Thời Gian Khởi Hành", "Thời Gian Đến", "Ngày Đăng Ký"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(JTDanhSachDangKyLichLamViec);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 758, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addGap(0, 0, Short.MAX_VALUE)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 232, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(49, 49, 49))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void JBDangKyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JBDangKyActionPerformed
        // TODO add your handling code here:
        
//        int MaNhanVien = DanhSachNhanVien.get(NhanVienListModel.getSelectedIndex()).getManv();
        int MaNhanVien = util.Global.employee.getManv();
        
        LichTrinh lt = DanhSachLichTrinhTheoTauVaTuyenDuong.get(ThoiGianKhoiHanhVaThoiGianDenListModel.getSelectedIndex());
        int MaLichTrinh = lt.getMaLichTrinh();
        java.sql.Date NgayDangKy = new java.sql.Date(Utils.getCurrentDate().getTime());
        String KetQua = dklvDao.DangKyLichLamViec(MaNhanVien, MaLichTrinh, NgayDangKy);
        if(KetQua.equals("")){
            DangKyLamViec dklv = new DangKyLamViec();
            dklv.setMaDangKyLamViec(DangKyLamViec.getNextMaxId());
            dklv.setMaNhanVien(MaNhanVien);
            dklv.setMaLichVanChuyen(MaLichTrinh);
            dklv.setTenNhanVien(util.Global.employee.getTen());
            dklv.setTenTau(TauListModel.getSelectedItem().toString());
            dklv.setTenTuyenDuong(TuyenDuongListModel.getSelectedItem().toString());
            dklv.setNgayDangKy(NgayDangKy);
            dklv.setThoiGianKhoiHanh(lt.getTGKhoiHanh());
            dklv.setThoiGianDen(lt.getTGDen());
            DanhSachDangKyLamViec.add(dklv);
            insertIntoTable(dklv);
        }else{
            JOptionPane.showMessageDialog(this, KetQua,"Thông báo",JOptionPane.ERROR_MESSAGE);
        }
        
    }//GEN-LAST:event_JBDangKyActionPerformed

    private void JBHuyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JBHuyActionPerformed
        // TODO add your handling code here:
        DongDangKyLamViecDuocChon = JTDanhSachDangKyLichLamViec.getSelectedRow();
        if(DongDangKyLamViecDuocChon == -1){
            return;
        }
        
        
        DangKyLamViec dklv = DanhSachDangKyLamViec.get(DongDangKyLamViecDuocChon);
        String kq = dklvDao.HuyLichLamViec(dklv.getMaNhanVien(),dklv.getMaLichVanChuyen());
        if(kq.equals("")){
            model.removeRow(DongDangKyLamViecDuocChon);
            DongDangKyLamViecDuocChon = -1;
        }else{
            JOptionPane.showMessageDialog(this, kq,"Thông báo",JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_JBHuyActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton JBDangKy;
    private javax.swing.JButton JBHuy;
    private javax.swing.JComboBox JCBTau;
    private javax.swing.JComboBox JCBTuyenDuong;
    private javax.swing.JTable JTDanhSachDangKyLichLamViec;
    private javax.swing.JTextField JTFNgayDangKy;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    // End of variables declaration//GEN-END:variables

    class MyComboBoxModel extends AbstractListModel implements ComboBoxModel{

        List<Object> model;

        Object selection = null;

        public MyComboBoxModel() {
            model = new ArrayList<Object>();
        }

        public MyComboBoxModel(List<Object> model){
            this.model = model;
        }


        @Override
        public int getSize() {
            return model.size();
        }

        @Override
        public Object getElementAt(int index) {
            return model.get(index);
        }

        @Override
        public void setSelectedItem(Object anItem) {
            if(anItem != selection){
                selection = anItem;
            }

        }

        public void setSelectedItem(int index){
            this.selection = model.get(index);
        }

        @Override
        public Object getSelectedItem() {
            return selection;
        }

        public int getSelectedIndex(){
            for(int i = 0; i < model.size();i++){
                if(model.get(i) == selection){
                    return i;
                }
            }
            return 0;
        }

        public void add(Object element) {
            if (model.add(element)) {
                fireContentsChanged(this, 0, getSize());
            }
        }

        public void addAll(Object elements[]) {
            Collection<Object> c = Arrays.asList(elements);
            model.addAll(c);
            fireContentsChanged(this, 0, getSize());
        }

        public void clear(){
            model.clear();
            fireContentsChanged(this, 0, getSize());
        }

        public boolean contains(Object element) {
            return model.contains(element);
        }

        public Object firstElement() {
            return model.get(0);
        }

        public Iterator iterator() {
            return model.iterator();
        }

        public Object lastElement() {
            return model.get(model.size() - 1);
        }

        public boolean removeElement(Object element) {
            boolean removed = model.remove(element);
            if (removed) {
                fireContentsChanged(this, 0, getSize());
            }
            return removed;
        }
    
    }
}




